package leetcode.jianzhioffer;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-01 16:12
 **/
public class JianZhiOffer58I {

    /*public String reverseWords(String s) {
        s = s.trim();
        String[] split = s.split("\\s+");
        StringBuilder builder = new StringBuilder();
        for (int i = split.length - 1; i >= 0; i--) {
            if (i == 0) {
                builder.append(split[i]);
            } else {
                builder.append(split[i]).append(" ");
            }
        }
        return builder.toString();
    }*/

    public String reverseWords(String s) {
        removeBlank(s);
        StringBuilder builder = new StringBuilder();
        int fast = s.length() - 1;
        int slow = fast;
        while (fast >= 0) {
            while (fast >= 0 && s.charAt(fast) != ' ') {
                fast--;
            }
            builder.append(s.substring(fast + 1, slow + 1)).append(" ");
            while (fast >= 0 && s.charAt(fast) == ' ') {
                fast--;
            }
            slow = fast;
        }
        return removeBlank(builder.toString());
    }

    private String removeBlank(String s) {
        int low = 0;
        int high = s.length() - 1;
        while (low <= s.length() && s.charAt(low) == ' ') {
            low++;
        }
        while (high >= low && s.charAt(high) == ' ') {
            high--;
        }
        return s.substring(low, high + 1);
    }
}
